//
//  MYXDetailViewModel.m
//  meiyinxiang
//
//  Created by apple on 2017/11/13.
//  Copyright © 2017年 hbjApple. All rights reserved.
//

#import "MYXDetailViewModel.h"
#import <UIImageView+WebCache.h>
#import "NearbyLuckyMoneyDetail.h"
#import "MYXRecieveMoneyListViewModel.h"
#import "MYY_User.h"
#import "AppDelegate.h"
#import "STInputBar.h"
/*
 @property(nonatomic,strong) NSString *  luckyMoneyId;
 @property(nonatomic,assign) double latitude;
 @property(nonatomic,assign) double longitude;
 @property(nonatomic,strong) NSString *  create_time;
 @property(nonatomic,strong) NSString *  update_time;
 @property(nonatomic,strong) NSString *  uid;
 @property(nonatomic,strong) NSString *  money;
 @property(nonatomic,strong) NSString *  title;
 @property(nonatomic,strong) NSString *  content;
 @property(nonatomic,strong) NSString *  file;
 @property(nonatomic,strong) NSString *  status;
 @property(nonatomic,strong) NSString *  sex;
 @property(nonatomic,strong) NSString *  tuijian;
 @property(nonatomic,strong) NSString *  radius;
 @property(nonatomic,strong) NSString *  ticket_id;
 @property(nonatomic,strong) NSString *  username;
 @property(nonatomic,strong) NSString *  userface;
 @property(nonatomic,strong) NSString *  my_money;
 @property (nonatomic,copy) NSArray
 <NearbyLuckyMoneyDetail>* list;
 */
@interface MYXDetailViewModel()<UITextViewDelegate>
{
    STInputBar *_inputBar;
//    UIView *commentsView;
//    UITextView *commentText;
}
@end
@implementation MYXDetailViewModel
+ (MYXDetailViewModel *)initWithNearLuckyListModel:(NearbyluckyMoneyDetailList *)nearLuckyDetailList{
    MYXDetailViewModel *detailViewModel = [[MYXDetailViewModel alloc] init];
    detailViewModel.luckyMoneyId = nearLuckyDetailList.luckyMoneyId;
    detailViewModel.latitude = nearLuckyDetailList.latitude;
    detailViewModel.longitude = nearLuckyDetailList.longitude;
    detailViewModel.create_time = nearLuckyDetailList.create_time;
    detailViewModel.update_time = nearLuckyDetailList.update_time;
    detailViewModel.uid = nearLuckyDetailList.uid;
    detailViewModel.money = nearLuckyDetailList.money;
    detailViewModel.title = nearLuckyDetailList.title;
    detailViewModel.content = nearLuckyDetailList.content;
    detailViewModel.smallLuckyMoneyId = nearLuckyDetailList.rpid;
    //添加图片url数组
    if (nearLuckyDetailList.file.length > 0) {
        NSArray *urls = [nearLuckyDetailList.file componentsSeparatedByString:@","];
        for (NSString *imgurl in urls) {
            NSString *fileimgurl = [NSString stringWithFormat:@"%@%@",MYXIMGBaseUrl,imgurl];
            [detailViewModel.file addObject:fileimgurl];
        }
        if (detailViewModel.file.count == 1) {//单张图片处理
            [detailViewModel caculateSinglePictureViewSize];
        }
    }
  
    detailViewModel.status = nearLuckyDetailList.status;
    detailViewModel.sex = nearLuckyDetailList.sex;
    detailViewModel.tuijian = nearLuckyDetailList.tuijian;
    detailViewModel.radius = nearLuckyDetailList.radius;
    detailViewModel.ticket_id = nearLuckyDetailList.ticket_id;
    detailViewModel.username = nearLuckyDetailList.username;
    detailViewModel.userface = [NSString stringWithFormat:@"%@%@",MYXIMGBaseUrl,nearLuckyDetailList.userface];
    detailViewModel.my_money = nearLuckyDetailList.my_money;
    detailViewModel.rcount = nearLuckyDetailList.rcount;
    NSInteger restMoneyCout = nearLuckyDetailList.rcount.integerValue - nearLuckyDetailList.restcount.integerValue;
    detailViewModel.restcount = [NSString stringWithFormat:@"%ld",restMoneyCout];
    detailViewModel.zancount = nearLuckyDetailList.zancount.integerValue > 0 ? nearLuckyDetailList.zancount : @"点赞";
    detailViewModel.commentcount = nearLuckyDetailList.commentcount.integerValue > 0 ? nearLuckyDetailList.commentcount : @"评论";
    detailViewModel.markcount = nearLuckyDetailList.markcount.integerValue > 0 ? nearLuckyDetailList.markcount : @"收藏";
    detailViewModel.comment_status = nearLuckyDetailList.comment_status;
    for (NearbyLuckyMoneyDetail *listModel in nearLuckyDetailList.list) {
        MYXRecieveMoneyListViewModel *listViewModel = [[MYXRecieveMoneyListViewModel alloc] initWithModel:listModel];
        [detailViewModel.marray addObject:listViewModel];
    }
  //  [detailViewModel.marray addObjectsFromArray:nearLuckyDetailList.list];
    detailViewModel.isSecondRefresh = NO;
    //FIXME:-添加是否已经打开红包
    detailViewModel.isreceived = nearLuckyDetailList.isreceived;
    detailViewModel.smallLuckyMoneyNum = nearLuckyDetailList.my_money;

    detailViewModel.content = nearLuckyDetailList.content;
    //计算pictureViewSize
    detailViewModel.pictureViewSize = [detailViewModel caculatePictureViewSize];
    //计算cell高度
    [detailViewModel caculateCellHeight];
    detailViewModel.page = 1;
    return detailViewModel;
}

- (void )caculateSinglePictureViewSize{

    
    [[[SDWebImageManager sharedManager] imageDownloader] downloadImageWithURL:[NSURL URLWithString:self.file[0]] options:(SDWebImageDownloaderUseNSURLCache) progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (image) {
            CGSize imageSize = image.size;
            CGFloat maxWidth = 200;
            CGFloat minWidth = 40;
            if (imageSize.width > maxWidth) {//图片过宽
                imageSize.width = 200;
                imageSize.height = imageSize.width * image.size.height / image.size.width;

            }
            if (imageSize.width < minWidth) {//图片过窄处理
                imageSize.width = 40;
                imageSize.height = imageSize.width * image.size.height / image.size.width / 4;

            }
            if (imageSize.height > 200 ){//高度过高
                imageSize.height = 200;
            }
            imageSize.height += MYXLuckyMoneyPictureViewOutterMargin/2;
            self.pictureViewSize = imageSize;
            [self caculateCellHeight];
            if (self.singleImgFinishBlock) {
                self.singleDownloaderFinished = YES;
                self.singleImgFinishBlock(YES);
            }
        }

    }] ;
}
- (CGSize )caculatePictureViewSize{
    if (self.file.count == 0 ) {
        return  CGSizeZero;
        
    }
    NSInteger row = (self.file.count - 1)/3 + 1;
    CGFloat height = MYXLuckyMoneyPictureViewOutterMargin;
    height += row * MYXLuckyMoneyPictureItemWith;
    
    self.pictureViewSize = CGSizeMake(MYXPictureViewWith, height);
    return self.pictureViewSize;
}
//计算cell总高度
- (void)caculateCellHeight{
    CGFloat topConsHeiht = 130.5;
    CGFloat iconAndMoneyLabelsideSpace = 10;
    CGFloat moneyLabelHeight = 42;
    CGFloat moneyAndCommendSpace = 10;
    CGFloat contentAndImgViewSpace = 0;
    CGFloat sideSpace = 15;
    CGFloat imgviewAndTimeLabelSpace = 5;
    CGFloat timeLabelHeight = 20;
    CGFloat commendViewHeight = 30;
    CGFloat bottomSpace = 10;
    CGSize labelViewSize = CGSizeMake(ScreenWidth - 2*sideSpace, CGFLOAT_MAX);
    UIFont  *originalFont = [UIFont systemFontOfSize:17];
    CGFloat labelHeiht = [self.content boundingRectWithSize:labelViewSize options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:originalFont} context:nil].size.height;
    CGFloat  heightCons = 200;
    if (self.file.count == 0) {
        heightCons = 0;
       // bottomSpace = -30;
    }else{
        heightCons = self.pictureViewSize.height;
    }
    if ([self.isreceived isEqualToString:@"0"]) {//未领取红包
        moneyLabelHeight = 0;
    }else{//已领取红包
         timeLabelHeight = 0;
        //imgviewAndTimeLabelSpace = 0;
    }
    self.cellHeight = topConsHeiht +iconAndMoneyLabelsideSpace +moneyLabelHeight + moneyAndCommendSpace + labelHeiht +contentAndImgViewSpace  + heightCons +imgviewAndTimeLabelSpace*2 + timeLabelHeight + commendViewHeight + bottomSpace;
}
- (void)getLuckyMoneywithCompletion:(finishBlock)completion{
    NSString *lat = [NSString stringWithFormat:@"%f",ApplicationDelegate.locationcoor.latitude];
    NSString *lon = [NSString stringWithFormat:@"%f",ApplicationDelegate.locationcoor.longitude];
    [[Http sharedInstance] uploadDataWithUrl:GetLuckyMoneyCount withParams:@{@"pid":self.luckyMoneyId,@"lat":lat,@"lng":lon} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:[self.luckyMoneyId dataUsingEncoding:NSUTF8StringEncoding]name:@"pid"];
        [formData appendPartWithFormData:[lat dataUsingEncoding:NSUTF8StringEncoding]name:@"lat"];
        [formData appendPartWithFormData:[lon dataUsingEncoding:NSUTF8StringEncoding]name:@"lng"];
     
        
    } completion:^(id data, NSError *error) {
        
        if (data) {
            int  nRet = [[data objectForKey:@"status"] intValue];
            NSString *message = data[@"message"];
            if (nRet == 1) {
                NSString *smallMoneyId = data[@"data"][@"id"];
                NSString *smallMoneyNum = data[@"data"][@"money"];
                self.smallLuckyMoneyId = smallMoneyId;
                self.smallLuckyMoneyNum = smallMoneyNum;
                self.isreceived = @"1";
                self.isMessageEnable = YES;
               // self.restcount.integerValue += 1;
                self.restcount = [NSString stringWithFormat:@"%ld",self.restcount.integerValue + 1];
                [self caculateCellHeight];//更新cell高度
                completion(YES,@"抢红包成功");
            }else{
                completion(NO,message);
            }
            
        }else{
            completion(NO,@"请求出错");
        }
        
        
    }];
//        [[Http sharedInstance] requestForMethod:POST Url:GetLuckyMoneyCount withParams:@{@"pid":self.luckyMoneyId} completion:^(id data, NSError *error) {
//            
//            
//        }];
  
}
- (void)leaveMessageWithConten:(NSString *)content Completion:(finishBlock)completion{

   
}
//加载更多抢红包
- (void)getMoneyDetailWithIsPullup:(BOOL)isPullup Completion:(finishBlock)completion{
    NSInteger pageSize = 5;
    if (isPullup) {
        self.page ++;
    }else{
        [self.marray removeAllObjects];
        self.page = 1;
    }
    NSString *pagesizeString = [NSString stringWithFormat:@"%ld",pageSize];
    NSString *page = [NSString stringWithFormat:@"%ld",self.page];
    [[Http sharedInstance] requestForMethod:GET Url:MYXLuckyMoneyDetail withParams:@{@"id":self.luckyMoneyId,@"page":page,@"size":pagesizeString} completion:^(id data, NSError *error) {
        if (data) {
            int  nRet = [[data objectForKey:@"status"] intValue];
            NSString *message = data[@"message"];
            if (nRet == 1) {
                NSMutableArray *list = [NSMutableArray array];
                NSError *err = nil;
                NSArray *dataArray = data[@"data"][@"list"];
               //  NSLog(@"pullup is coming___________________________%@",dataArray);

                if (dataArray.count > 0) {
                    list = [NearbyLuckyMoneyDetail arrayOfModelsFromDictionaries:dataArray error:&err];
                    for (NearbyLuckyMoneyDetail *listModel in list) {
                        MYXRecieveMoneyListViewModel *listViewModel = [[MYXRecieveMoneyListViewModel alloc] initWithModel:listModel];
                        [self.marray addObject:listViewModel];
                    }
                    if (dataArray.count == 5) {
                        completion(YES,message);
                    }else{
                        completion(NO,message);
                    }
                }else{
                    completion(NO,message);

                }
               
            }else{
                completion(NO,message);
            }
        }else{
            completion(NO,@"请求出错");
            // completion(NO,@"请求出错");
        }
    }];
}
#pragma mark - 添加键盘
- (void)hidekeybord{
    [_inputBar removeFromSuperview];
    _inputBar = nil;
}
- (void)createCommentsView {
    if (!_inputBar) {
        
        _inputBar = [STInputBar inputBar];
        _inputBar.center = CGPointMake(CGRectGetWidth(ApplicationDelegate.window.frame)/2, CGRectGetHeight(ApplicationDelegate.window.bounds)-CGRectGetHeight(_inputBar.frame)+CGRectGetHeight(_inputBar.frame)/2);
        [_inputBar setFitWhenKeyboardShowOrHide:YES];
        _inputBar.placeHolder = @"来说点什么吧...";
    }
    [ApplicationDelegate.window addSubview:_inputBar];
    __weak typeof(self) weakSelf = self;
    [_inputBar setDidSendClicked:^(NSString *text) {
        weakSelf.inputbarString = text;
            if (text.length > 0) {
            
                NSDictionary *para = @{@"pid":weakSelf.luckyMoneyId,@"content":text};
                [[Http sharedInstance] requestForMethod:POST Url:LeaveMessage_URL withParams:para completion:^(id data, NSError *error) {

                    if (data) {
                        NSString *message = data[@"message"];
                        if ([data[@"status"] intValue] == 1) {
                            //更新评论数据
                            [weakSelf updateListData];
                          //  [commentText resignFirstResponder];
                            [SVProgressHUD showSuccessWithStatus:@"评论成功"];
                           weakSelf.finishmsgBlock(YES);
                        }else{
                            //    [SVProgressHUD showErrorWithStatus:message];
                           weakSelf.finishmsgBlock(NO);
                            ShowSVProgressErrorMessage(message);
                        }
                    }else{
                        ShowSVProgressErrorMessage(@"请求出错");
                        // [SVProgressHUD showErrorWithStatus:@"请求出错"];
                    }
                }];
            }
    }];
    //让textView成为第一响应者（第一次）这次键盘并未显示出来，（个人觉得这里主要是将commentsView设置为commentText的inputAccessoryView,然后再给一次焦点就能成功显示）
}
- (void)showCommentTextWithFinshBlock:(finishLeaveMessageBlock)leavemsgBlock {
    self.finishmsgBlock = leavemsgBlock;
    [self createCommentsView];
   // [commentText becomeFirstResponder];//再次让textView成为第一响应者（第二次）这次键盘才成功显示
}
//- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
//{
//    if ([text isEqualToString:@"\n"]) //获取键盘中发送事件（回车事件）
//    {
//        if (textView.text.length > 0) {
//            if (!self.smallLuckyMoneyNum) {//未抢到红包无法评论
//                ShowSVProgressErrorMessage(@"抢到红包后才可以评论");
//                return NO;
//            }
//            NSDictionary *para = @{@"pid":self.luckyMoneyId,@"content":textView.text};
//            [[Http sharedInstance] requestForMethod:POST Url:LeaveMessage_URL withParams:para completion:^(id data, NSError *error) {
//
//                if (data) {
//                    NSString *message = data[@"message"];
//                    if ([data[@"status"] intValue] == 1) {
//                        //更新评论数据
//                        [self updateListData];
//                     //   [commentText resignFirstResponder];
//                        [SVProgressHUD showSuccessWithStatus:@"评论成功"];
//                        finishmsgBlock(YES);
//                    }else{
//                    //    [SVProgressHUD showErrorWithStatus:message];
//                        finishmsgBlock(NO);
//                        ShowSVProgressErrorMessage(message);
//                    }
//                }else{
//                    ShowSVProgressErrorMessage(@"请求出错");
//                   // [SVProgressHUD showErrorWithStatus:@"请求出错"];
//                }
//            }];
//        }
//
//        //[self sendClick];  //处理键盘的发送事件
//    }
//    return YES;
//}
- (NSMutableArray *)marray{
    if (_marray == nil) {
        _marray = [NSMutableArray array];
        
    }
    return _marray;
}
- (void)updateListData{
        for ( MYXRecieveMoneyListViewModel *model in self.marray) {
            if ([MYY_User readUserFromFile].uid.intValue == model.tid.intValue) {
                model.content = self.inputbarString;
            }
        }
//        if (!haven) {
//            NearbyLuckyMoneyDetail *detailModel = [[NearbyLuckyMoneyDetail alloc] init];
//            detailModel.userface = [MYXMemberMdel sharedInstance].userinfo.image;
//            detailModel.username = [MYXMemberMdel sharedInstance].userinfo.nickname;
//            detailModel.content = commentText.text;
//            detailModel.num = self.smallLuckyMoneyNum;
//            if (self.list.count > 0) {
//                [self.marray addObject:detailModel];
//                [self.marray addObjectsFromArray:self.list];
//            }else{
//                [self.marray addObject:detailModel];
//               }
//        }
}
- (NSMutableArray *)file{
    if (_file == nil) {
        _file = [NSMutableArray array];
    }
    return _file;
}
@end
